`

loop, we define a block of commands that are run against each value in the list,

and each value in the list is assigned to a variable name we define.

Listing 2-13 shows the syntax of a for loop.

for variable_name in LIST; do

# run some commands for each item in the sequence

done

Listing 2-13

The for loop syntax

A simple way to use a for loop is to execute the same command a number of

times. For example, the following code prints the numbers 1 through 10:

#!/bin/bash

for index in $(seq 1 10); do

echo "${index}"

done

Save and run this script. You should see the following output:

1

2

3

4

5

6

7

8

9

10

A more practical example might use a for loop to run commands against a

bunch of IP addresses passed on the command line. The script in Listing 2-14

retrieves all arguments passed to the script, then iterates through them and prints a

message for each:

#!/bin/bash

for ip_address in "$@"; do

echo "Taking some action on IP address ${ip_address}"

done

Listing 2-14

A for loop to iterate through command line arguments

Save this script as for_loop_arguments.sh and run it as follows:

$ chmod u+x for_loop_arguments.sh

./for_loop_arguments.sh 10.0.0.1 10.0.0.2 192.168.1.1 192.168.1.2

Taking some action on IP address 10.0.0.1

Taking some action on IP address 10.0.0.2

--snip--

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks